package pe.gob.mimp.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import pe.gob.mimp.util.UploadedFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.FilenameUtils;

@Controller
@RequestMapping(value = "/upload")
public class UploadController {
	@RequestMapping(value = "/file", method = RequestMethod.POST)
	public @ResponseBody
	List<UploadedFile> upload(@RequestParam("file") MultipartFile file) {
		String fileName = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		Calendar c = Calendar.getInstance();
		
		
		List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();
		UploadedFile archivo = new UploadedFile(FilenameUtils.getBaseName(file.getOriginalFilename())+"_"+c.hashCode()+"."+FilenameUtils.getExtension(file.getOriginalFilename()), Long.valueOf(file.getSize()).intValue(),file.getOriginalFilename());

		uploadedFiles.add(archivo);
		try {
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				fileName = "/home/csocial/" + archivo.getName();
				outputStream = new FileOutputStream(fileName);

				int readBytes = 0;
				byte[] buffer = new byte[10000];
				while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
					outputStream.write(buffer, 0, readBytes);
				}
				outputStream.close();
				inputStream.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return uploadedFiles;
	}
}
